package com.huanwei.map;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.facebook.stetho.common.LogUtil;
import com.huanwei.cc.R;
import com.huanwei.cc.base.BaseActivity2;
import com.huanwei.cc.bean.ShiShiben;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import lib.kingja.switchbutton.SwitchMultiButton;

/**
 * 校園详情
 */
public class School_details_Activity extends BaseActivity2 implements LocationSource, AMapLocationListener, AMap.OnMarkerClickListener, AMap.InfoWindowAdapter {


    Bundle mSavedInstanceState;
    @BindView(R.id.vvv)
    SwitchMultiButton vvv;


    private AMap aMap;
    private MapView mapView;
    private UiSettings mUiSettings;
    private OnLocationChangedListener mLocationLinstener;
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;

    private View infoWindow = null;
    private TextView mTvDogName;
    private LinearLayout mLlother;
    private Marker mMarkMyLocation;
    private Marker currentMarker;
    private double mLocatinLat;
    private double mLocationLon;

    //    113.758231,23.026998
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSavedInstanceState = savedInstanceState;
        setContentView(R.layout.activity_marker);
        ButterKnife.bind(this);

        initView();

        vvv.setOnSwitchListener(new SwitchMultiButton.OnSwitchListener() {
            @Override
            public void onSwitch(int position, String tabText) {
                Log.e("8888", "xx" + position);
                qiehuan(position);
//                Toast.makeText(MarkerActivity.this, tabText, Toast.LENGTH_SHORT).show();
            }
        });
        RelativeLayout viewById = (RelativeLayout) findViewById(R.id.img_back);
        viewById.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();

            }
        });


    }

    double latitude;
    double longtitude;

    protected void initView() {

        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(mSavedInstanceState);// 此方法必须重写
        if (aMap == null) {
            aMap = mapView.getMap();
            aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
                @Override
                public void onMapLoaded() {
                    aMap.setMapType(AMap.MAP_TYPE_NORMAL);


                }
            });
            aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
                @Override
                public void onMapClick(LatLng latLng) {
                    latitude = latLng.latitude;
                    longtitude = latLng.longitude;
//                    Toast.makeText(ShiShiDingWei_9_Activity.this, "是否要到这个位置！", Toast.LENGTH_SHORT).show();
                    showDialog(String.valueOf(latitude), String.valueOf(longtitude));
                }
            });

        }
        mUiSettings = aMap.getUiSettings();
        mUiSettings.setLogoPosition(2);//设置高德地图logo位置
        mUiSettings.setZoomControlsEnabled(true);
        mUiSettings.setTiltGesturesEnabled(true);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(20));
        aMap.setLocationSource(this);// 设置定位监听
        aMap.setMyLocationEnabled(true);
        aMap.setOnMarkerClickListener(this);
        aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式

        initLocation();
        //中心点设置

        onTouchHide();
        /**
         * 获得实时定位
         */
        getRealTimeTrack();
//        new TimeThread().start(); //启动新的线程
    }

    class TimeThread extends Thread {
        @Override
        public void run() {
            do {
                try {
                    Thread.sleep(60 * 1000);
                    Message msg = new Message();
                    msg.what = 1;  //消息(一个整型值)
                    mHandler.sendMessage(msg);// 每隔1秒发送一个msg给mHandler
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (true);
        }
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    getRealTimeTrack();


                    break;
                default:
                    break;

            }
        }
    };


    /**
     * 系统小蓝点
     * 设定
     */
    private void setMyLocationStyleIcon() {
//		 自定义系统定位小蓝点

        MyLocationStyle myLocationStyle = new MyLocationStyle();
        ImageView iv = new ImageView(this);
        FrameLayout.LayoutParams fmIv = new FrameLayout.LayoutParams(1, 1);
        iv.setImageResource(R.drawable.che);
        iv.setLayoutParams(fmIv);
        BitmapDescriptor markerIcon = BitmapDescriptorFactory.fromView(iv);
        myLocationStyle.myLocationIcon(markerIcon);// 设置小蓝点的图标
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        myLocationStyle.strokeWidth(0f);// 设置圆形的边框粗细
        myLocationStyle.anchor(0.5f, 0.9f);
        aMap.setMyLocationStyle(myLocationStyle);

    }


    private void initLocation() {

        locationClient = new AMapLocationClient(getApplicationContext());
        locationOption = new AMapLocationClientOption();

        // 设置定位模式为高精度模式
        locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        locationOption.setNeedAddress(true);
        // 设置定位监听
        locationClient.setLocationListener(this);
        //每两秒定位一次
        locationOption.setInterval(2000);
        locationOption.setOnceLocation(true);
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();

    }


    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mLocationLinstener = onLocationChangedListener;
    }

    @Override
    public void deactivate() {
        mLocationLinstener = null;
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation != null
                    && aMapLocation.getErrorCode() == 0) {

                if (mLocationLinstener != null) {
                    mLocationLinstener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                }
                mLocatinLat = aMapLocation.getLatitude();
                mLocationLon = aMapLocation.getLongitude();
//                setMyLocationStyleIcon();
//                setMyStopLoca(new LatLng(mLocatinLat, mLocationLon));
//                setAroundMark(new LatLng(mLocatinLat, mLocationLon));


            }
        } else {
            //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
            LogUtil.d("location Error, ErrCode:"
                    + aMapLocation.getErrorCode() + ", errInfo:"
                    + aMapLocation.getErrorInfo());
        }
    }

    private void setcenter() {
        LatLng marker1 = new LatLng(23.026998, 113.758231);
        //设置中心点和缩放比例
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(marker1));
        aMap.moveCamera(CameraUpdateFactory.zoomTo(12));
    }

//    private void setMyStopLoca(final LatLng latlng) {
//        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 17f));
//
//        if (mMarkMyLocation != null) {
//            mMarkMyLocation.destroy();
//            mMarkMyLocation = null;
//        }
//
//
//        if (mMarkMyLocation == null) {
//            final MarkerOptions markerOptions = new MarkerOptions();
//            //markerOptions.snippet(dogId);
//            // 设置Marker点击之后显示的标题
//            markerOptions.setFlat(false);
//            markerOptions.anchor(0.5f, 0.7f);
//            markerOptions.zIndex(25);
//            markerOptions.zIndex(90);
//            MyLocationMarkerView myLocationMarkerView = new MyLocationMarkerView(ShiShiDingWei_9_Activity.this, getmAdaptationClass());
//
//
//            BitmapDescriptor markerIcon = BitmapDescriptorFactory.fromView(myLocationMarkerView);
//
//
//            markerOptions.icon(markerIcon);
//            markerOptions.position(new LatLng(latlng.latitude + 0.1, latlng.longitude + 0.1));
//            mMarkMyLocation = aMap.addMarker(markerOptions);
//
//        } else {
//            mMarkMyLocation.setPosition(latlng);
//        }
//    }

    MyLocationMarkerView manMarkerWoman;
    MarkerOptions markerOptionsWoman;
    BitmapDescriptor markerIconWoman;

    /**
     * 设置码
     *
     * @param latlng
     */
    private void setAroundMark(final LatLng latlng, String name, int icon, String jieshao) {


        markerOptionsWoman = new MarkerOptions();
        // 设置Marker点击之后显示的标题
        markerOptionsWoman.setFlat(true);
        markerOptionsWoman.anchor(0.5f, 0.7f);
        markerOptionsWoman.zIndex(25);
        markerOptionsWoman.zIndex(90);
        markerOptionsWoman.title(name);
        markerOptionsWoman.snippet(name);

        manMarkerWoman = new MyLocationMarkerView(School_details_Activity.this, getmAdaptationClass());
//        manMarkerWoman.setmCirHead2(R.drawable.che);
//        BitmapDescriptor markerIcon = BitmapDescriptorFactory.fromView(manMarkerWoman);
//        markerOptionsWoman.icon(markerIcon);

        Log.e("11111", "xx" + name);
        manMarkerWoman.setmCirHead2(icon);
        markerIconWoman = BitmapDescriptorFactory.fromView(manMarkerWoman);

        markerOptionsWoman.icon(markerIconWoman);
        markerOptionsWoman.position(new LatLng(latlng.latitude, latlng.longitude));
        aMap.addMarker(markerOptionsWoman);


    }


    @Override
    public boolean onMarkerClick(final Marker marker) {


        if (currentMarker != null) {
            currentMarker.hideInfoWindow();
            currentMarker = null;
        }
        //新建currentMarker保存状态，当点击非mark区域的时候将marker的InfoWindow隐藏
        currentMarker = marker;

        marker.showInfoWindow();
        mLlother.setBackgroundResource(R.drawable.infowinow_background);
        return true;


    }


    @Override
    public View getInfoWindow(Marker marker) {
        infoWindow = getLayoutInflater().inflate(R.layout.infowindow_other, null);
        mLlother = (LinearLayout) infoWindow.findViewById(R.id.ll_info_other);
        mTvDogName = (TextView) infoWindow.findViewById(R.id.dog_name);
        mTvDogName.setTextColor(getResources().getColor(R.color.main_font_green));
        mTvDogName.setText(marker.getTitle());


        return infoWindow;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    private void onTouchHide() {
        aMap.setOnMapTouchListener(new AMap.OnMapTouchListener() {
            @Override
            public void onTouch(MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        if (currentMarker != null) {
                            currentMarker.hideInfoWindow();
                            currentMarker = null;

                        }
                        break;
                }
            }
        });
    }

    List<ShiShiben.DataBean> ccList = new ArrayList<ShiShiben.DataBean>();

    public void getRealTimeTrack() {
        ccList.add(new ShiShiben.DataBean(" 新青年广场", 118.4840, 32.522, "xx", R.drawable.dingwei ))
        ;

        ccList.add(new ShiShiben.DataBean("第一食堂", 118.4830, 32.455, "xx", R.drawable.dingwei));


        ccList.add(new ShiShiben.DataBean("南林超市", 118.4832, 32.456, "xx", R.drawable.dingwei));

        ccList.add(new ShiShiben.DataBean("新体育馆", 118.4843, 32.456, "xx", R.drawable.dingwei));

        ccList.add(new ShiShiben.DataBean("第二食堂", 118.4831, 32.457, "xx", R.drawable.dingwei));

        ccList.add(new ShiShiben.DataBean("林大超市", 118.4828, 32.454, "xx", R.drawable.dingwei));

        ccList.add(new ShiShiben.DataBean("地球仪", 118.4828, 32.444, "xx", R.drawable.dingwei));

        ccList.add(new ShiShiben.DataBean("林学院", 118.4831, 32.444, "xx", R.drawable.dingwei));

        ccList.add(new ShiShiben.DataBean("生物与环境学院", 118.4834, 32.443, "xx", R.drawable.dingwei));

        ccList.add(new ShiShiben.DataBean("南林樱花大道", 118.4833, 32.447, "xx", R.drawable.dingwei));

        ccList.add(new ShiShiben.DataBean("化学工程学院", 118.4841, 32.446, "xx", R.drawable.dingwei));

        ccList.add(new ShiShiben.DataBean("土木工程、机械电子工程学院", 118.4837, 32.445, "xx",
                R.drawable.dingwei));

        ccList.add(new ShiShiben.DataBean("材料科学与工程学院", 118.4835, 32.447, "xx", R.drawable.dingwei))
        ;

        ccList.add(new ShiShiben.DataBean("教学主楼", 118.4840, 32.447, "xx", R.drawable.dingwei));

        ccList.add(new ShiShiben.DataBean("第五教学楼", 118.4838, 32.451, "xx", R.drawable.dingwei));

        ccList.add(new ShiShiben.DataBean("新图书馆", 118.4844, 32.445, "xx", R.drawable.dingwei));

        ccList.add(new ShiShiben.DataBean("佐香苑商业街", 118.4845, 32.441, "xx", R.drawable.dingwei));

        ccList.add(new ShiShiben.DataBean("南京林业大学研究楼", 118.4847, 32.437, "xx", R.drawable.dingwei))
        ;

        ccList.add(new ShiShiben.DataBean("二村餐厅", 118.4848, 32.450, "xx", R.drawable.dingwei));

        ccList.add(new ShiShiben.DataBean("教九综合院楼", 118.4911, 32.448, "xx", R.drawable.dingwei));

        ccList.add(new ShiShiben.DataBean("南林大厦", 118.4820, 32.439, "xx", R.drawable.dingwei));

        ccList.add(new ShiShiben.DataBean("信息科学技术学院", 118.4821, 32.441, "xx", R.drawable.dingwei))
        ;

        ccList.add(new ShiShiben.DataBean("老图书馆", 118.4832, 32.449, "xx", R.drawable.dingwei));

        ccList.add(new ShiShiben.DataBean("老体育馆", 118.4842, 32.501, "xx", R.drawable.dingwei));

        List<ShiShiben.DataBean> data = ccList;
        for (int i = 0; i < data.size(); i++) {

            setAroundMark(new LatLng(data.get(i).getLatitude(), data.get(i).getLongitude()), data.get(i).getName(), data.get(i).getICON(), data.get(i).getJieShao());
        }


    }


    public void qiehuan(int key) {
        if (key == 1) {
            if (aMap == null) {
                aMap = mapView.getMap();
                aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
                    @Override
                    public void onMapLoaded() {
                        aMap.setMapType(AMap.MAP_TYPE_SATELLITE);

                    }
                });

            } else {
                aMap.setMapType(AMap.MAP_TYPE_SATELLITE);
            }

        } else {
            if (aMap == null) {
                aMap = mapView.getMap();
                aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
                    @Override
                    public void onMapLoaded() {


                    }
                });

            } else {
                aMap.setMapType(AMap.MAP_TYPE_NORMAL);
            }

        }

    }


    private void showDialog(final String Latitude, final String Longitude) {
  /*
  这里使用了 android.support.v7.app.AlertDialog.Builder
  可以直接在头部写 import android.support.v7.app.AlertDialog
  那么下面就可以写成 AlertDialog.Builder
  */
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("是否要到目的地附近？");
        builder.setNegativeButton("取消", null);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (AMapUtil.isInstallByRead("com.autonavi.minimap")) {

                    AMapUtil.goToNaviActivity(School_details_Activity.this, "test", null, String.valueOf(Latitude), String.valueOf(Longitude), "1", "2");
                } else {
                    Toast.makeText(School_details_Activity.this, "请安装高德地图", Toast.LENGTH_SHORT).show();
                }
            }
        });
        builder.show();
    }
}
